import {_decorator, Component, Sprite, SubContextView,SpriteFrame,Prefab,instantiate,ScrollView,UITransform,Vec2,v2,Label,Color,color} from 'cc';
import Platform, {PlatformType} from "./Platform";
import {GameMain} from "./GameMain";
import {RankItem} from "./RankItem";
import {locationAPIKey} from "./GameConfig";

const { ccclass, property } = _decorator;

@ccclass('RankUI')
export class RankUI extends Component {

    @property({type:Prefab})
    rankItemPrefab:Prefab=null;

    @property({type:SpriteFrame})
    defaultHeader:SpriteFrame=null;

    private windowNode:Node=null;
    private worldBtnSprite:Sprite=null;
    private cityBtnSprite:Sprite=null;

    private worldRankPanel:Node=null;

    private worldScrollView:ScrollView=null;
    private cityScrollView:ScrollView=null;
    private contentUITransform:UITransform=null;

    private worldRankScoreLabel:Label=null;
    private levelLabel:Label=null;

    public rankItemCache=[];

    public inRankNum:number=-1;

    private inited:boolean=false;

    public static readonly rankItemInterval:number=16;
    public static readonly maxItemNum:number=100;

    onLoad()
    {

        //this.subContextView.node.active=false;
    }

    start() {

    }

    init()
    {
        this.windowNode=this.node.getChildByName("window");
        this.worldBtnSprite=this.windowNode.getChildByName("worldBtn").getComponent(Sprite);
        this.cityBtnSprite=this.windowNode.getChildByName("cityBtn").getComponent(Sprite);

        this.worldRankPanel=this.windowNode.getChildByName("worldRankPanel");

        this.worldScrollView=this.worldRankPanel.getChildByName("ScrollView").getComponent(ScrollView);
        this.cityScrollView=this.worldRankPanel.getChildByName("cityScrollView").getComponent(ScrollView);
        this.contentUITransform=this.worldScrollView.content.getComponent(UITransform);

        this.worldRankScoreLabel=this.worldRankPanel.getChildByName("tipLabel").getComponent(Label);
        this.levelLabel=this.worldRankPanel.getChildByName("levelLabel").getComponent(Label);

        for(let i=0;i<RankUI.maxItemNum;i++)
        {
            let itemObj=instantiate(this.rankItemPrefab);
            this.rankItemCache.push(itemObj);
        }

        this.inited=true;
    }

    public getRankItem()
    {
        if(this.rankItemCache.length>0)
        {
            return this.rankItemCache.pop();
        }
        else
        {
            for(let i=0;i<RankUI.maxItemNum;i++)
            {
                let itemObj=instantiate(this.rankItemPrefab);
                this.rankItemCache.push(itemObj);
            }
            return this.rankItemCache.pop();
        }
    }

    public show()
    {
        if(!this.inited)
            this.init();
        this.node.active=true;



        this.rankSel("city");

    }

    public onWorldBtnClicked()
    {
        this.rankSel("world");
    }

    public onCityBtnClicked()
    {
        this.rankSel("city");
    }

    public rankSel(rankType:string)
    {
        if(rankType==="world")
        {
            this.worldRankPanel.active=true;
            this.worldScrollView.node.active=true;
            this.cityScrollView.node.active=false;

            this.worldBtnSprite.color=Color.WHITE;
            this.cityBtnSprite.color=Color.GRAY;

            this.onWorldRankShow();
            this.levelLabel.string="玩到第 "+ (GameMain.instance.gameData.curLevelId+1)+"关";
        }
        else if(rankType==="city")
        {
            /*
            wx.getSetting({
                success:(res)=> {

                    if (!res.authSetting['scope.userLocation']) {
                        wx.authorize({
                            scope: 'scope.userLocation',
                            success () {

                            }
                        })
                    }
                }
            });*/

            this.worldRankPanel.active=true;

            this.worldScrollView.node.active=false;
            this.cityScrollView.node.active=true;

            this.worldBtnSprite.color=Color.GRAY;
            this.cityBtnSprite.color=Color.WHITE;

            this.worldRankScoreLabel.string="当前城市:"+ GameMain.instance.gameData.city;

            this.onCityRankShow();
        }
    }


    public onCityRankShow()
    {
        if(Platform.currentPlatform!==PlatformType.WECHAT)
            return;

        this.levelLabel.node.active=true;
        this.levelLabel.string="您已贡献 "+ GameMain.instance.gameData.cityStar+" 星星";

        //使用本地存储的city请求数据(显示速度更快)
        GameMain.instance.getCityRankData();

        //获取location
        wx.getLocation({
            type: 'wgs84',
             success:(res)=> {
                const latitude = res.latitude;
                const longitude = res.longitude;
                const speed = res.speed;
                const accuracy = res.accuracy;
                console.log("** wx.GetLocatioin成功 la="+res.latitude+" lo="+res.longitude);

                //请求city查询
                let urlStr:string="https://api.tianditu.gov.cn/geocoder?postStr={'lon':" + res.longitude+",'lat':"+ res.latitude+",'ver':1}&type=geocode&tk="+locationAPIKey;

                wx.request({
                    url:urlStr,
                    data: {},
                    header: {
                        'Content-Type': 'application/json'
                    },
                    success: (res)=> {
                        // success
                        //console.log(" **  city="+ JSON.stringify(res));
                        //console.log(("*** city="+  res.data.result.addressComponent.city));
                        if(res.data.msg==="ok")
                        {
                            let city:string=res.data.result.addressComponent.city;
                            GameMain.instance.wxUser.setCity(city);
                            GameMain.instance.gameData.updateCity(city);
                            this.worldRankScoreLabel.string="当前城市:"+city;
                            this.levelLabel.node.active=true;

                        }
                        else
                        {
                            this.levelLabel.node.active=false;
                            this.worldRankScoreLabel.string="当前城市:未定位";
                        }
                    },
                    fail: ()=> {
                        // fail  定位失败
                        this.levelLabel.node.active=false;
                        this.worldRankScoreLabel.string="当前城市:未定位";
                    },
                })
            }
        });
    }

    public onWorldRankShow()
    {
        if(Platform.currentPlatform!==PlatformType.WECHAT)
            return;

        if(this.inRankNum>0)
        {
            this.worldRankScoreLabel.string = "当前排名:"+this.inRankNum;
        }
        else
        {
            this.worldRankScoreLabel.string = "当前排名:-";
        }
        GameMain.instance.wxUser.getUserInfo();
        GameMain.instance.getScoreRankData();
    }

    public clearRankItems()
    {
        for(let i=0;i<this.worldScrollView.content.children.length;i++)
        {
            this.rankItemCache.push(this.worldScrollView.content.children[i]);
        }
        this.worldScrollView.content.removeAllChildren(true);
    }

    public clearCityRankItems()
    {
        for(let i=0;i<this.cityScrollView.content.children.length;i++)
        {
            this.rankItemCache.push(this.cityScrollView.content.children[i]);
        }
        this.cityScrollView.content.removeAllChildren(true);
    }

    public setCityRankData(data)
    {
        if(!data || data.length<=0)
            return;

        this.clearCityRankItems();

        //是否上榜
        let isInRank:boolean=false;
        let inRankNum:number=0;

        let ystart:number=-RankUI.rankItemInterval - RankItem.ItemHeight*0.5;
        for(let i=0;i<data.length;i++)
        {
            let rankItemObj=this.getRankItem();
            this.cityScrollView.content.addChild(rankItemObj);
            let rankItem:RankItem=rankItemObj.getComponent("RankItem");
            rankItem.setData(i, data[i]);

            rankItemObj.setPosition(0, ystart - i*(RankUI.rankItemInterval+RankItem.ItemHeight),0);
            //console.log(" ** i="+i+"   data="+JSON.stringify(data[i]));

            if(data[i].city===GameMain.instance.wxUser.city)
            {
                isInRank=true;
                inRankNum=i+1;
                rankItem.setInRank(true);
            }
            else
            {
                rankItem.setInRank(false);
            }
        }

        this.contentUITransform.height= data.length*RankItem.ItemHeight + (data.length+1)* RankUI.rankItemInterval + 60;

        if(isInRank)
        {
            /*
            let scrollTo:number=(inRankNum)/RankUI.maxItemNum;

            let maxOffset:Vec2=this.worldScrollView.getMaxScrollOffset();
            this.scheduleOnce(()=>{
                this.worldScrollView.scrollToOffset(new Vec2(0,maxOffset.y * scrollTo), 3);
            },1);*/

            //this.worldRankScoreLabel.string="当前排名:"+inRankNum;
        }
        else
        {
            /*
            if(!GameMain.instance.wxUser.userInfoSetted)
                this.worldRankScoreLabel.string="未授权,请先授权";
            else
                this.worldRankScoreLabel.string="未上榜,请加油哦";
             */
        }
    }

    public setWorldRankData(data)
    {
        if(!data || data.length<=0)
            return;

        this.clearRankItems();

        //是否上榜
        let isInRank:boolean=false;
        let inRankNum:number=0;

        let ystart:number=-RankUI.rankItemInterval - RankItem.ItemHeight*0.5;
        for(let i=0;i<data.length;i++)
        {
            if(data[i].maxNum<2)
                continue;
            let rankItemObj=this.getRankItem();
            this.worldScrollView.content.addChild(rankItemObj);
            let rankItem:RankItem=rankItemObj.getComponent("RankItem");
            rankItem.setData(i, data[i]);

            rankItemObj.setPosition(0, ystart - i*(RankUI.rankItemInterval+RankItem.ItemHeight),0);
            //console.log(" ** i="+i+"   data="+JSON.stringify(data[i]));

            if(data[i]._openid===GameMain.instance.wxUser.openId)
            {
                isInRank=true;
                inRankNum=i+1;
                rankItem.setInRank(true);
            }
            else
            {
                rankItem.setInRank(false);
            }
        }

        this.contentUITransform.height= data.length*RankItem.ItemHeight + (data.length+1)* RankUI.rankItemInterval + 60;

        if(isInRank)
        {
            let scrollTo:number=(inRankNum)/RankUI.maxItemNum;

            let maxOffset:Vec2=this.worldScrollView.getMaxScrollOffset();
            this.scheduleOnce(()=>{
                this.worldScrollView.scrollToOffset(new Vec2(0,maxOffset.y * scrollTo), 3);
            },1);

            this.worldRankScoreLabel.string="当前排名:"+inRankNum;
            this.inRankNum=inRankNum;
        }
        else
        {
            if(!GameMain.instance.wxUser.userInfoSetted)
                this.worldRankScoreLabel.string="未授权,请先授权";
            else
                this.worldRankScoreLabel.string="未上榜,请加油哦";
            this.inRankNum=-1;
        }
    }

    public close()
    {
        //this.subContextView.node.active=false;
        this.node.active=false;
    }

    /*
    update(deltaTime: number) {
        
    }*/
}

